package com.qf.elasticsearch.query.impl;

import com.qf.elasticsearch.query.QueryOtherService;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * create by 郑大仙丶
 * 2019/11/22 23:19
 */
@Service
public class QueryOtherServiceImpl implements QueryOtherService {


    @Autowired
    private RestHighLevelClient client;


    @Override
    public void scrollQuery(String index, String type) throws IOException {
        SearchRequest request = new SearchRequest(index);
        request.types(type);

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        builder.size(2);
        request.source(builder);

        Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1));  //1分钟
        request.scroll(scroll);

        SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
        String scrollId = resp.getScrollId();
        SearchHit[] hits = resp.getHits().getHits();
        System.out.println("---------首页--------");
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
        while(hits != null && hits.length > 0){
            SearchScrollRequest req = new SearchScrollRequest(scrollId);
            req.scroll(scroll);

            resp = client.scroll(req, RequestOptions.DEFAULT);
            hits = resp.getHits().getHits();
            System.out.println("---------下一页--------");
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsMap());
            }
        }
        ClearScrollRequest scrollRequest = new ClearScrollRequest();
        scrollRequest.addScrollId(scrollId);
        ClearScrollResponse clearScrollResponse = client.clearScroll(scrollRequest, RequestOptions.DEFAULT);
    }
}
